package com.lzs.baseruku.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzs.baseruku.feign.StockFeign;
import com.lzs.baseruku.service.*;
import com.lzs.entity.*;
import com.lzs.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ymx
 * @since 2020-11-25
 */
@RestController
@RequestMapping("/baseruku/warehousing")
@Api(value = "入库管理文档")
public class WarehousingController {
    @Autowired
    private WarehousingService warehousingService;
    @Autowired
    private WarehousingDetailService warehousingDetailService;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private LocatorService locatorService;
    @Autowired
    private ReceiveService receiveService;
    @Autowired
    private ReceiveDetailService receiveDetailService;
    @Autowired
    private StockFeign stockFeign;
    @Autowired
    private CommodityService commodityService;


    @ApiOperation(value = "删除时根据接货编号修改接货单状态")
    @GetMapping("/updateReceiveByReceiveno/{receiveno}")
    public void updateReceiveByReceiveno(@PathVariable String receiveno){

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("receiveno",receiveno);
        Receive receive = this.receiveService.getOne(queryWrapper);
        Long id=receive.getId();
        receive.setState("2");

        QueryWrapper queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("id",id);
        this.receiveService.update(receive,queryWrapper1);

    }

    @ApiOperation(value = "根据入库订单编号修改该订单状态")
    @GetMapping("/updateWarehousingState/{warehousingno}")
    public R updateWarehousingState(@PathVariable String warehousingno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("warehousingno",warehousingno);
        Warehousing warehousing = this.warehousingService.getOne(queryWrapper);
        warehousing.setState("1");
        boolean b = this.warehousingService.update(warehousing, queryWrapper);
        if (b) {
            return R.ok().message("操作成功");
        } else {
            return R.error().message("操作失败");
        }
    }

    @ApiOperation(value = "根据pid查看入库订单明细")
    @GetMapping("/LookWarehousingDetailByPid/{pid}")
    public R LookWarehousingDetailByPid(@PathVariable Long pid){
        QueryWrapper<WarehousingDetail> queryWrapper=new QueryWrapper();
        queryWrapper.eq("pid",pid);
        List<WarehousingDetail> warehousingDetails = warehousingDetailService.list(queryWrapper);
        return R.ok().data("warehousingDetails",warehousingDetails);
    }

    @ApiOperation(value = "根据入库订单编号查询id")
    @GetMapping("/selectIdByWarehousingno/{warehousingno}")
    public R selectIdByWarehousingno(@PathVariable String warehousingno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("warehousingno",warehousingno);
        Warehousing warehousing = this.warehousingService.getOne(queryWrapper);
        return R.ok().data("warehousing",warehousing);
    }

    @ApiOperation(value = "开始入库时修改该接货订单状态")
    @GetMapping("/updateReceiveState/{receiveno}")
    public R updateReceiveState(@PathVariable String receiveno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("receiveno",receiveno);
        Receive receive = this.receiveService.getOne(queryWrapper);
        receive.setState("3");
        boolean b = this.receiveService.update(receive, queryWrapper);
        if (b) {
            return R.ok().message("操作成功");
        } else {
            return R.error().message("操作失败");
        }
    }

    @ApiOperation(value = "查询所有已审核的接货单号")
    @GetMapping("/selectReceive")
    public R selectReceive(){
        QueryWrapper<Receive> queryWrapper=new QueryWrapper();
        queryWrapper.eq("state","2");
        List<Receive> list = this.receiveService.list(queryWrapper);
        return R.ok().data("list",list);
    }

    @ApiOperation(value = "添加入库货位")
    @PostMapping("/insertWarehousing")
    public R insertWarehousing(@RequestBody Warehousing warehousing){
        boolean b = this.warehousingService.save(warehousing);
        if (b){
            return R.ok().message("添加成功");
        }else {
            return R.error().message("添加失败");
        }
    }

    @ApiOperation(value = "查询所有入库信息")
    @PostMapping("/selectWarehousing/{page}/{limit}")
    public R selectWarehousing(@PathVariable Integer page, @PathVariable Integer limit, @RequestBody Warehousing warehousing){
        Page<Warehousing> warehousingPage = warehousingService.selectwarehousing(page, limit, warehousing);
        return R.ok().data("warehousingPage",warehousingPage);
    }

    @ApiOperation(value = "根据ID删除入库订单")
    @DeleteMapping("/deleteWarehousing/{id}")
    public R deleteWarehousing(@PathVariable Long id){
        Warehousing warehousing = this.warehousingService.getById(id);
        if (warehousing.getState().equals("2")) {
            return R.error().message("已审核，禁止修改");
        }else {
            try{
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("pid",id);
                this.warehousingDetailService.remove(queryWrapper);
                this.warehousingService.removeById(id);
                return R.ok().message("删除成功");
            }catch (Exception e){
                return R.error().message("删除失败");
            }
        }
    }

    @ApiOperation(value = "审核入库货位订单")
    @PostMapping("/updateState")
    public R updateState(@RequestBody List<Long> ids){
        for (int i=0;i<ids.size();i++){
            Warehousing warehousing = warehousingService.getById(ids.get(i));
            if (warehousing.getState().equals("2")){
                return R.error().message("订单已审核，不能重复审核");
            }
            if (warehousing.getState().equals("0")){
                return R.error().message("订单为录入完毕，不能审核");
            }
        }
        R r = warehousingService.updateState(ids, "2");
        for (int i=0;i<ids.size();i++) {
            Warehousing warehousing = warehousingService.getById(ids.get(i));
            Long id=warehousing.getId();//入库id
            String warehousingno=warehousing.getWarehousingno();//入库单号
            Long warehouseid=warehousing.getWarehouseid();//仓库id
            String locatorcode=warehousing.getLocatorcode();//库位编码
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("pid",id);
            List<WarehousingDetail> list = this.warehousingDetailService.list(queryWrapper);
            for (int j=0;j<list.size();j++){
                String commoditybar=list.get(j).getCommoditybar();
                Integer qty=list.get(j).getQty();
//                Map map=new HashMap();
//                map.put("warehousingno",warehousingno);
//                map.put("warehouseid",warehouseid);
//                map.put("locatorcode",locatorcode);
//                map.put("commoditybar",commoditybar);
//                map.put("qty",qty);

                Stock stock=new Stock();
                stock.setCommoditybar(commoditybar);
                stock.setLocatorcode(locatorcode);
                stock.setWarehouseid(warehouseid);
                stock.setBillno(warehousingno);
                stock.setCqty(qty);
                stockFeign.addStock(stock);
            }
        }
        return r;
    }

    @ApiOperation(value = "撤销审核入库货位订单")
    @PostMapping("/NoUpdateState")
    public R NoUpdateState(@RequestBody List<Long> ids){
        for (int i=0;i<ids.size();i++){
            Warehousing warehousing = warehousingService.getById(ids.get(i));
            if (warehousing.getState().equals("0")||warehousing.getState().equals("1")){
                return R.error().message("订单未审核，不能撤销审核");
            }
        }
        R r = warehousingService.updateState(ids, "1");
        for (int i=0;i<ids.size();i++) {
            Warehousing warehousing = warehousingService.getById(ids.get(i));
            Long id = warehousing.getId();//入库id
            String warehousingno = warehousing.getWarehousingno();//入库单号
            Long warehouseid = warehousing.getWarehouseid();//仓库id
            String locatorcode = warehousing.getLocatorcode();//库位编码
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("pid", id);
            List<WarehousingDetail> list = this.warehousingDetailService.list(queryWrapper);
            for (int j = 0; j < list.size(); j++) {
                String commoditybar = list.get(j).getCommoditybar();
                Integer qty = list.get(j).getQty();
                Stock stock=new Stock();
                stock.setCommoditybar(commoditybar);
                stock.setLocatorcode(locatorcode);
                stock.setWarehouseid(warehouseid);
                stock.setBillno(warehousingno);
                stock.setCqty(qty);
                stockFeign.reduceStock(stock);
            }
        }
        return r;
    }

    @ApiOperation(value = "录入商品明细")
    @PostMapping("/insertWarehousingDetail")
    public R insertWarehousingDetail(@RequestBody WarehousingDetail warehousingDetail){
        Long pid=warehousingDetail.getPid();
        String commoditybar=warehousingDetail.getCommoditybar();

        QueryWrapper queryWrapper5=new QueryWrapper();
        queryWrapper5.eq("bar",commoditybar);
        Commodity commodity1 = this.commodityService.getOne(queryWrapper5);
        String name=commodity1.getName();
        warehousingDetail.setCommodityname(name);

        Integer ruqty=warehousingDetail.getQty();
        Warehousing warehousing = this.warehousingService.getById(pid);
        String receiveno=warehousing.getReceiveno();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("receiveno",receiveno);
        Receive receive = this.receiveService.getOne(queryWrapper);
        Long id=receive.getId();
        QueryWrapper queryWrapper2=new QueryWrapper();
        queryWrapper2.eq("pid",id);
        queryWrapper2.eq("commoditybar",commoditybar);
        ReceiveDetail receiveDetail = this.receiveDetailService.getOne(queryWrapper2);
        Integer jieqty=receiveDetail.getQty();
        if (ruqty>jieqty){
            return R.error().message("入库数量大于接货数量");
        }else {
            Long pid2=warehousingDetail.getPid();
            String commoditybar2=warehousingDetail.getCommoditybar();
            Integer qty1=warehousingDetail.getQty();
            QueryWrapper queryWrapper3=new QueryWrapper();
            queryWrapper3.eq("pid",pid2);
            queryWrapper3.eq("commoditybar",commoditybar2);
            WarehousingDetail warehousingDetail1 = this.warehousingDetailService.getOne(queryWrapper3);
            if (warehousingDetail1!=null){
                Integer qty0=warehousingDetail1.getQty();
                Long id2=warehousingDetail1.getId();
                Integer qty2=qty0+qty1;
                if (qty2<=jieqty) {
                    warehousingDetail1.setQty(qty2);
                    QueryWrapper queryWrapper4 = new QueryWrapper();
                    queryWrapper4.eq("id", id2);
                    boolean b = this.warehousingDetailService.update(warehousingDetail1, queryWrapper4);
                    if (b) {
                        return R.ok().message("操作成功");
                    } else {
                        return R.error().message("操作失败");
                    }
                }else {
                    return R.error().message("数量不符");
                }
            }else {
                boolean b = warehousingDetailService.save(warehousingDetail);
                if (b) {
                    return R.ok().message("操作成功");
                } else {
                    return R.error().message("操作失败");
                }
            }
        }

    }

    @ApiOperation(value = "根据id查看入库商品明细")
    @GetMapping("/LookWarehousingDetailById/{id}")
    public R LookWarehousingDetailById(@PathVariable Long id){
        QueryWrapper<WarehousingDetail> queryWrapper=new QueryWrapper();
        queryWrapper.eq("pid",id);
        List<WarehousingDetail> warehousingDetails = this.warehousingDetailService.list(queryWrapper);
        return R.ok().data("warehousingDetails",warehousingDetails);
    }

//    @ApiOperation(value = "根据id查看入库商品明细")
//    @GetMapping("/LookWarehousingDetailById/{page}/{limit}/{id}")
//    public R LookWarehousingDetailById(@PathVariable Integer page, @PathVariable Integer limit, @PathVariable Long id){
//        Page<WarehousingDetail> warehousingDetails = warehousingDetailService.lookWarehousingDetail(page,limit,id);
//        return R.ok().data("warehousingDetails",warehousingDetails);
//    }

//    @ApiOperation(value = "查看入库商品明细")
//    @GetMapping("/LookWarehousingDetail/{page}/{limit}")
//    public R LookWarehousingDetail(@PathVariable Integer page, @PathVariable Integer limit,@RequestBody Warehousing warehousing){
//        Page<WarehousingDetail> warehousingDetails = warehousingDetailService.lookWarehousingDetail(page,limit,id);
//        return R.ok().data("warehousingDetails",warehousingDetails);
//    }

    @ApiOperation(value = "下拉所有仓库")
    @GetMapping("/selectAllWarehouse")
    public R selectAllWarehouse(){
        List<Warehouse> warehouses = warehouseService.list();
        return R.ok().data("warehouses",warehouses);
    }

    @ApiOperation(value = "下拉所有仓库下的入库区货位")
    @GetMapping("/selectAllWarehouseLocator/{id}")
    public R selectAllWarehouseLocator(@PathVariable Long id){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("type","2");
        queryWrapper.eq("warehouseid",id);
        List<Locator> locators = this.locatorService.list(queryWrapper);
        return R.ok().data("locators",locators);
    }

    @ApiOperation(value = "根据接货单号下拉所有商品编码")
    @GetMapping("/selectCommodity/{receiveno}")
    public R selectCommodity(@PathVariable String receiveno){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("receiveno",receiveno);
        Receive receive = receiveService.getOne(queryWrapper);
        Long id=receive.getId();
        QueryWrapper<ReceiveDetail> queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("pid",id);
        List<ReceiveDetail> receiveDetails = this.receiveDetailService.list(queryWrapper1);
        return R.ok().data("receiveDetails",receiveDetails);
    }
}

